import { OnInit, Component, Output, EventEmitter, ViewChild } from '@angular/core';
import { DictionaryService } from 'src/app/project/service/icm/icm-global/dictionary/dictionary.service';
import { SystemDictionaryDTO } from 'src/app/project/model/icm/icm-global/dictionary/dictionary.dto';
import { FormGroup, FormBuilder, Validators, FormControl, ValidationErrors, NgForm } from '@angular/forms';
import { Observable, Observer } from 'rxjs';
import { OperationNotification, OperationType } from 'src/app/project/model/common/operation-notification';
import { NzMessageService } from 'ng-zorro-antd';
import { FormUtil } from '@shared/utils/form-util';

@Component({
  selector: 'app-dictionary-detail',
  templateUrl: './dictionary-detail.component.html',
  styles: [],
})
export class DictionaryDetailComponent implements OnInit {
  constructor(private dictionaryService: DictionaryService, private fb: FormBuilder, private msg: NzMessageService) {
    this.validateForm = this.fb.group({
      code: ['', [Validators.required], [this.codeAsyncValidator]],
      name: ['', [Validators.required], [this.nameAsyncValidator]],
    });
  }

  /**
   * 数据变化通知事件
   */
  @Output()
  notification = new EventEmitter<OperationNotification<SystemDictionaryDTO>>();

  /**
   * form组件
   */
  @ViewChild('dictionaryForm', { static: false })
  public dictionaryForm: NgForm;

  /**
   * 表单
   */
  validateForm: FormGroup;

  /**
   * 是否预览
   */
  isPreView = false;

  /**
   * 表单窗体打开/关闭控制
   */
  isVisible = false;

  /**
   * 调用后台API标志
   */
  loading = false;

  /**
   * 字典编码是否已存在，true为已存在
   */
  isExist: boolean;

  /**
   * 字典
   */
  dictionary: SystemDictionaryDTO = {
    id: null,
    code: '',
    name: '',
    systemInitialized: false,
    values: [],
  };

  /**
   * 校验字典编码是否已存在
   */
  codeAsyncValidator = (control: FormControl) =>
    new Observable((observer: Observer<ValidationErrors | null>) => {
      this.dictionaryService.checkoutCodeIsExist(null, control.value).subscribe(data => {
        this.isExist = data.data;
      });
      setTimeout(() => {
        if (this.isExist) {
          // you have to return `{error: true}` to mark it as an error event
          observer.next({ error: true, duplicated: true });
        } else if (control.value.includes(' ')) {
          observer.next({ error: true, blank: true });
        } else {
          observer.next(null);
        }
        observer.complete();
      }, 1000);
    });

  /**
   * 校验字典名称
   */
  nameAsyncValidator = (control: FormControl) =>
    new Observable((observer: Observer<ValidationErrors | null>) => {
      setTimeout(() => {
        if (control.value.includes(' ')) {
          observer.next({ error: true, blank: true });
        } else {
          observer.next(null);
        }
        observer.complete();
      }, 1000);
    });

  /**
   * 编辑/预览
   */
  preview() {
    // 编辑状态下isPreView为false，isReView为true
    this.isPreView = !this.isPreView;
  }

  /**
   * 修改窗口状态
   */
  handleCancel() {
    this.isVisible = false;
    FormUtil.resetForm(this.dictionaryForm.form);
  }

  /**
   * 保存前验证数据
   */
  beforeSave() {
    if (this.dictionary.code === '') {
      this.msg.error('字典编码必填');
      return false;
    }
    if (this.dictionary.name === '') {
      this.msg.error('字典名称必填');
      return false;
    }
    return true;
  }
  /**
   * 保存
   */
  save() {
    if (!this.beforeSave()) {
      return;
    }
    this.loading = true;
    if (!this.dictionary.id) {
      // id为空，新建字典
      this.dictionaryService.create(this.dictionary).subscribe(
        data => this.afterItemSaved(data, OperationType.CREATE),
        null,
        () => this.afterCallCompleted(),
      );
    } else {
      // id不为空，修改保存字典
      this.dictionaryService.complete(this.dictionary.id, this.dictionary).subscribe(
        data => this.afterItemSaved(data, OperationType.CREATE),
        null,
        () => this.afterCallCompleted(),
      );
    }
  }

  /**
   * 数据保存后的通用操作
   *
   * @param data 保存的数据
   * @param operation 操作类型
   */
  private afterItemSaved(data: SystemDictionaryDTO, operation: OperationType): void {
    this.loading = false;
    this.handleCancel();
    this.notification.emit({
      operation,
      data,
    });
    this.msg.success('保存成功!');
  }

  /**
   * API调用完成后的操作
   */
  private afterCallCompleted(): void {
    this.loading = false;
  }

  /**
   * 修改或新增字典
   * @param isPreView 是否预览
   * @param item 字典信息
   */
  edit(isPreView: boolean, item: SystemDictionaryDTO) {
    this.isPreView = isPreView;

    // 初始化字典
    this.dictionary = this.initDictionary(item);
    this.isVisible = true;
  }

  initDictionary(item: SystemDictionaryDTO): SystemDictionaryDTO {
    return {
      id: item ? item.id : null,
      code: item ? item.code : '',
      name: item ? item.name : '',
      systemInitialized: item ? item.systemInitialized : false,
      values: item ? item.values : [],
    };
  }
  ngOnInit() {}
}
